<template>
  <BasicModal v-bind="$attrs" title="换绑手机" :width="modalWidth" :okButtonProps="{ disabled: false }" @register="registerModal" :destroyOnClose="true" @ok="handleSubmit">
    <div style="color:red;;font-weight: bold">只允许换绑一次，如果选择申请函方式换绑，需上传会员换绑申请函，要求身份证放在申请函上照片</div>
    <BasicForm @register="registerForm"></BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { BasicModal, useModalInner } from '@apps/antd-admin/src/components/modal';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/form';
import { changeMobileFormSchema } from '../data/data';
import { ref, unref } from 'vue';
import { changeMobile, getUserInfo } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';
import { useMessage } from '@apps/antd-admin/src/hooks/web/useMessage';

const { getIsMobile } = useAppInject();
const modalWidth = ref('40%');
if (unref(getIsMobile)) {
  modalWidth.value = '80%';
}
const { createConfirm } = useMessage();
const emit = defineEmits(['success', 'register']);
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  schemas: changeMobileFormSchema,
  showActionButtonGroup: false,
});
const isUpdate = ref(true);
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  resetFields();
  data.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    let record = data.record;
    let queryData = await getUserInfo({ userId: record.userId });
    setFieldsValue(queryData);
  }
});

async function handleSubmit() {
  try {
    const values = await validate();
    console.info(values);
    if (unref(isUpdate)) {
      createConfirm({
        iconType: 'info',
        title: '换绑只允许一次，请检查信息正确并谨慎操作',
        content: '是否确认换绑？',
        onOk: async () => {
          setModalProps({ confirmLoading: true });
          await changeMobile(values)
            .then(res => {
              closeModal();
              emit('success', false);
              setModalProps({ confirmLoading: false });
            })
            .catch(error => {
              setModalProps({ confirmLoading: false });
            });
        },
      });
    }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
